package com.reebake.ideal.security.oauth2.config;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@Slf4j
public class Oauth2ResourceServerConfig {
	
	@Autowired
    private com.reebake.ideal.security.oauth2.properties.OAuth2ResourceProperties OAuth2ResourceProperties;

	@Bean
	SecurityFilterChain oauth2ResourceServerSecurityFilterChain(HttpSecurity http) throws Exception {
		Assert.notEmpty(OAuth2ResourceProperties.getResourceUrls(), "oauth2 resources url must not be null");
		log.info("启动SecurityFilterChain: oauth2-resource-server ");
		http.securityMatcher(ArrayUtil.toArray(OAuth2ResourceProperties.getResourceUrls(), String.class)).authorizeHttpRequests((authorize) -> authorize
	            .requestMatchers(ArrayUtil.toArray(OAuth2ResourceProperties.getPermitAllUrls(), String.class)).permitAll()
	            .anyRequest().authenticated()
	        )
			.oauth2ResourceServer((resourceServer) -> resourceServer
	        .jwt(Customizer.withDefaults()))
	        ;
	    
	    http.csrf(csrf -> csrf.disable());
        http.cors(Customizer.withDefaults());
	    return http.build();
	}

}
